package com.linrung.sf.scheduler.utils;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * json 美化
 * @author wurenlong
 */
public class JsonFormater {

	public static String format(String json) {
		StringBuilder indent = new StringBuilder();// 缩进
		StringBuilder sb = new StringBuilder();
		for (char c : json.toCharArray()) {
			switch (c) {
			case '{':
				indent.append(" ");
				sb.append("{\n").append(indent);
				break;
			case '}':
				indent.deleteCharAt(indent.length() - 1);
				sb.append("\n").append(indent).append("}");
				break;
			case '[':
				indent.append(" ");
				sb.append("[\n").append(indent);
				break;
			case ']':
				indent.deleteCharAt(indent.length() - 1);
				sb.append("\n").append(indent).append("]");
				break;
			case ',':
				sb.append(",\n").append(indent);
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}

	public static String format(JSONObject json) {
		return format(json.toString());
	}
	
	public static String format(Object obj) {
		return format(JsonObjectUtils.parseObject(obj).toString());
	}
	
	public static String format(JSONArray json) {
		return format(json.toString());
	}
	
	public static <T> String format(List<T> obj) {
		return format(JsonObjectUtils.parseArray(obj).toString());
	}
}
